<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Models\Paper;
use App\Models\Question;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PaperController extends Controller
{
    /**
     * 试卷列表（含题目数量）
     * GET /api/teacher/papers
     */
    public function index(Request $request)
    {
        // 从请求体获取参数
        $name = $request->input('name');
        $type = $request->input('type');
        $status = $request->input('status');
        $teacherId = $request->input('teacher_id'); // 添加教师ID筛选参数
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        // 查询试卷（不再限制为当前教师）
        $query = Paper::with('teacher:id,name'); // 预加载教师信息

        // 搜索条件
        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }
        if (!empty($type)) {
            $query->where('type', $type);
        }
        if (isset($status)) {
            $query->where('status', $status);
        }
        // 添加按教师ID筛选的条件
        if (!empty($teacherId)) {
            $query->where('teacher_id', $teacherId);
        }

        // 分页查询
        $papers = $query->paginate($pageSize, ['*'], 'page', $page);
        $paperItems = $papers->items();

        // 计算每个试卷的题目数量，并加载题目列表
        foreach ($paperItems as $paper) {
            $paper->question_count = $paper->questionCount;
            $paper->questions = $paper->questions;
        }

        return $this->paginated($paperItems, $papers);
    }

    /**
     * 新增/编辑试卷（含题目关联）
     * POST/PUT /api/teacher/papers
     */
    public function save(Request $request)
    {
        // 验证参数
        $request->validate([
            'id' => 'nullable|integer|exists:papers,id', // 编辑时必传
            'name' => 'required|string|max:100',
            'duration' => 'required|integer|min:1',
            'type' => 'required|in:0,1', // 0:随堂测验, 1:考试
            'status' => 'boolean',
            'question_ids' => 'required|array', // 题目ID数组
            'question_ids.*' => 'integer|exists:questions,id' // 每个ID必须存在
        ]);

        $teacherId = auth('admin')->id();
        $paperId = $request->input('id');

        // 新增或更新试卷基本信息
        $paper = Paper::updateOrCreate(
            ['id' => $paperId], // 编辑条件
            [
                'name' => $request->input('name'),
                'duration' => $request->input('duration'),
                'type' => $request->input('type'),
                'teacher_id' => $teacherId,
                'status' => $request->input('status', 1)
            ]
        );

        // 关联题目（同步：删除原有关联，添加新关联）
        $paper->questions()->sync($request->input('question_ids'));

        $message = $paperId ? '试卷更新成功' : '试卷创建成功';
        return $this->success($paper, $message);
    }

    /**
     * 题库列表（供选择题目时使用）
     * GET /api/teacher/questions
     */
    public function questionList(Request $request)
    {
        // 从请求体获取参数
        $type = $request->input('type'); // 题型筛选
        $status = $request->input('status', 1); // 默认只看正常状态
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        $query = Question::query();

        // 筛选条件
        if (isset($type)) {
            $query->where('type', $type);
        }
        if (isset($status)) {
            $query->where('status', $status);
        }

        // 分页查询
        $questions = $query->paginate($pageSize, ['*'], 'page', $page);

        return $this->paginated($questions->items(), $questions);
    }
}
